﻿using System.ComponentModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using MvvmTutorials.ToolkitMessages.Models;

namespace MvvmTutorials.ToolkitMessages.ViewModels;

public partial class StudentFormViewModel : ObservableRecipient, IRecipient<ValueChangedMessage<bool>>
{
    private bool allowAddNew;
    // NotifyPropertyChangedRecipients标记会在属性改变后调用BrodCast方法
    // 本质是WeakReferenceMessenger.Default.Send<PropertyChangedMessage<string>>(this)
    [ObservableProperty]
    [NotifyPropertyChangedRecipients]
    private string name;

    [ObservableProperty]
    [NotifyPropertyChangedRecipients]
    private string _class;

    [ObservableProperty]
    [NotifyPropertyChangedRecipients]
    private string phone;
    // protected override void OnPropertyChanged(PropertyChangedEventArgs e)
    // {
    //     base.OnPropertyChanged(e);
    //     if (e.PropertyName != null)
    //         WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<string>(this, e.PropertyName, null, e.PropertyName));
    // }
    public string SqlQuery =>
        $"INSERT INTO Students (Name, Class, Phone) VALUES ('{Name}', '{Class}', '{Phone}')";

    [RelayCommand(CanExecute = nameof(CanAddNew))]
    private void AddNew()
    {
        WeakReferenceMessenger.Default.Send(
            new ValueChangedMessage<Student>(new(Name, Class, Phone))
        );
        this.Name = string.Empty;
        this.Class = string.Empty;
        this.Phone = string.Empty;
    }
    private bool CanAddNew() => allowAddNew;

    public void Receive(ValueChangedMessage<bool> message)
    {
        allowAddNew = message.Value;
        AddNewCommand.NotifyCanExecuteChanged();

    }
}
